<?php
namespace Admin\Controller;
use Think\Controller;
class CateController extends CommonController{

    public function index(){
        //查询一级分类
        $where = array(
            'good_parent_id'=>0
        );
        $cate = M('good_cate')->where($where)->select();
        
        //通过一级分类id获取二级分类
        foreach($cate as $k=>$v){
            $cate[$k]['data'] = M('good_cate')->where('good_parent_id='.$v['id'])->select();
        }
        $this->assign('cate',$cate);
        $this->display();
    }

    //添加分类
    public function add_cate(){
        $parent_id = I('parent_id');
        $good_cate_name = I('good_cate_name');
        //判断parent_id如果等于0，则表示添加一级分类
        if($parent_id == 0){
            $data['good_parent_id'] = 0;
        }else{
            $data['good_parent_id'] = $parent_id;
        }
        $data['good_cate_name'] = $good_cate_name;
        $data['add_time'] = date('Y-m-d H:i:s',time());
        if(M('good_cate')->add($data)){
            $this->success('添加成功',U('index'));
        }else{
            $this->error('添加失败');
        }
    }

    //删除分类
    public function cateDel(){
        $cate_id = I('cate_id');
        $info = M('good_cate')->where('id='.$cate_id)->delete();
        if($info){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    //添加分类图片
    public function cate_picture(){
        if(IS_POST){
            $where = array(
                'id'=>I('cate_id')
            );
            $picture = uploadPicture();
            if($picture){
                $data['cate_picture'] = $picture;
                if(false ===M('good_cate')->where($where)->save($data)){
                    $this->error('上传失败');
                }else{
                    $this->success('图片已上传',U('index'));
                }
            }else{
                $this->error('上传失败');
            }
        }

        $id = I('cate_id');
        $this->assign('cate_id',$id);
        $this->display();
    }
}